package cn.iocoder.yudao.module.handguard.controller.app.wechat;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import java.util.Date;
 
 
@Component
public class AccessToken {
 
    public static TokenBean tokenBean = new TokenBean();

    /**
     * 获取微信模板发送所需Token
     * 每次获取有效期为2个小时
     * @return token
     */
    public static String getAccessToken(){
        tokenBean = null;
        if (tokenBean == null || tokenBean.getDate() == null || tokenBean.getDate().getTime() < new Date().getTime()){
            tokenBean = new TokenBean();
            //发送模板请求接口
            String result = HttpRequest.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb02ec49730579186&secret=e77405dc4196cb3615bef38f2bf68c84")
                    .header(Header.USER_AGENT, "Mozilla/5.0 (Linux; Android 8.0.0; SM-N9500 Build/R16NW; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.83 Mobile Safari/537.36 T7/10.13 baiduboxapp/10.13.0.11 (Baidu; P1 8.0.0)")//头信息，多个头信息多次调用此方法即可
                    .timeout(10000)//超时，毫秒
                    .execute().body();
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String access_token = (String) jsonObject.get("access_token");
            tokenBean.setToken(access_token);
            Date date = new Date(new Date().getTime() + 7200 * 1000);
            tokenBean.setDate(date);
            return access_token;
        }else{
            return tokenBean.getToken();
        }
    }
}